package com.nginxmanager.server.serverIpm;

import com.nginxmanager.domain.Proxy;
import com.nginxmanager.server.NginxConf;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018-01-04.
 */
@Service
public class NginxConfImpl implements NginxConf{

    //通过nginx.conf文件查询代理的服务器
    @Override
    public List<String> findUptStream(String str) {
        File file = new File(str+"\\conf\\nginx.conf");

        BufferedReader reader = null;
        List<String> serverList = new ArrayList<>();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            while((tempString=reader.readLine()) != null){
                Pattern p = Pattern.compile("(.*)(upstream)(.*)");
                Matcher m = p.matcher(tempString);
                if (m.matches()){
                    System.out.println("line " + line + ": " + tempString);
                    tempString=reader.readLine();
                    while (!tempString.contains("}")){
                        p = Pattern.compile("(.*)(server)(.*)(;)");
                        m = p.matcher(tempString);
                        if (m.matches()){
                            serverList.add(m.group(3));
                            System.out.println("测试扫描 " + line + ":" + tempString);
                        }
                        tempString=reader.readLine();
                    }

                }
                System.out.println("line " + line + ": " + tempString);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return serverList;
    }


    //通过文件读取，备份，写入，代替，完成增加代理服务器
    @Override
    public void addUptStream(String str, Proxy proxy) {
        Proxy proxy1 = proxy;
        File file = new File(str+"\\conf\\nginx.conf");
        File fileOut = new File(str+"\\conf\\nginx123.conf");
        BufferedReader reader = null;
        BufferedWriter bw = null;
        String newStream ="server "+proxy1.getIp();
        if (!proxy1.getPort().isEmpty()){
            newStream = newStream+":"+proxy1.getPort();
        }
        if (!proxy1.getWeight().isEmpty()){
            newStream = newStream+" weight="+proxy1.getWeight();
        }
        if (!proxy1.getMax_fails().isEmpty()){
            newStream = newStream+" max_fails="+proxy1.getMax_fails();
        }
        if (!proxy1.getFail_timeout().isEmpty()){
            newStream = newStream+" fail_timeout="+proxy1.getFail_timeout()+"s";
        }
        String tempString = null;
        try {
            if (!fileOut.exists()) {
                fileOut.createNewFile();
            }
            FileWriter fw = new FileWriter(fileOut);
            bw = new BufferedWriter(fw);
            reader = new BufferedReader(new FileReader(file));
            int line = 1;
            while((tempString=reader.readLine()) != null){
                Pattern p = Pattern.compile("(.*)(upstream)(.*)");
                Matcher m = p.matcher(tempString);
                bw.write(tempString + "\n");
                if (m.matches()){
                    bw.write("        "+newStream+";"+"\n");
                    System.out.println("增加: " + newStream);
                }
                line++;
            }
            reader.close();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        file.delete();
        fileOut.renameTo(file);
    }

    //遍历nginx.conf文件
    @Override
    public List<String> readUptStream(String str) {
        File file = new File(str+"\\conf\\nginx.conf");

        BufferedReader reader = null;
        List<String> serverList = new ArrayList<>();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            while((tempString=reader.readLine()) != null){
                System.out.println("line " + line + ": " + tempString);
                serverList.add(tempString);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return serverList;
    }

    ////通过文件读取，备份，写入，代替，完成删除代理服务器
    @Override
    public Integer deleteUptStream(String str, Proxy proxy) {
        int stu = 0;
        File file = new File(str+"\\conf\\nginx.conf");
        File fileOut = new File(str+"\\conf\\nginx123.conf");
        BufferedReader reader = null;
        BufferedWriter bw = null;
        String deleteStream = proxy.getIp()+":"+proxy.getPort();
        String tempString = null;
        try {
            if (!fileOut.exists()) {
                fileOut.createNewFile();
            }
            FileWriter fw = new FileWriter(fileOut);
            bw = new BufferedWriter(fw);
            reader = new BufferedReader(new FileReader(file));
            int line = 1;
            while((tempString=reader.readLine()) != null){
                Pattern p = Pattern.compile("(.*)("+deleteStream+")(.*)");
                Matcher m = p.matcher(tempString);
                if (m.matches()){
                    System.out.println("删除: " + deleteStream);
                    stu = 1;
                    continue;
                }
                bw.write(tempString + "\n");
                line++;
            }
            reader.close();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        file.delete();
        fileOut.renameTo(file);
        return stu;
    }
    //通过文件读取，备份，写入，代替，完成修改代理服务器
    @Override
    public void gaiUptStream(String str, Proxy newProxy) {
        File file = new File(str+"\\conf\\nginx.conf");
        File fileOut = new File(str+"\\conf\\nginx123.conf");
        BufferedReader reader = null;
        BufferedWriter bw = null;
        String tempString = null;
        String oldStream = newProxy.getIp();
        String newStream ="server "+newProxy.getIp();
        if (!newProxy.getPort().isEmpty()){
            newStream = newStream+":"+newProxy.getPort();
            oldStream = oldStream+":"+newProxy.getPort();
        }
        if (!newProxy.getWeight().isEmpty()){
            newStream = newStream+" weight="+newProxy.getWeight();
        }
        if (!newProxy.getMax_fails().isEmpty()){
            newStream = newStream+" max_fails="+newProxy.getMax_fails();
        }
        if (!newProxy.getFail_timeout().isEmpty()){
            newStream = newStream+" fail_timeout="+newProxy.getFail_timeout()+"s";
        }
        List<String> serverList = new ArrayList<>();
        try {
            if (!fileOut.exists()) {
                fileOut.createNewFile();
            }
            FileWriter fw = new FileWriter(fileOut);
            bw = new BufferedWriter(fw);
            reader = new BufferedReader(new FileReader(file));
            int line = 1;
            while((tempString=reader.readLine()) != null){
                Pattern p = Pattern.compile("(.*)("+oldStream+")(.*)");
                Matcher m = p.matcher(tempString);
                if (m.matches()){
                    bw.write("        "+newStream + ";"+"\n");
                    System.out.println("修改: " + newStream);
                    continue;
                }
                bw.write(tempString + "\n");
                line++;
            }
            reader.close();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        file.delete();
        fileOut.renameTo(file);
    }
//conf文件状态监测，返回0是文件没有负载均衡初始化，1是建立了upStream，没有建立proxy_pass。2是建立了proxy_pass，没有建立upStream。返回3是初始化完成，可以调用接口修改文件
    @Override
    public int seeUptStream(String str) {
        int type = 0 ;
        boolean t1=false,t2=false;
        File file = new File(str+"\\conf\\nginx.conf");

        BufferedReader reader = null;
        List<String> serverList = new ArrayList<>();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            while((tempString=reader.readLine()) != null){
                Pattern p = Pattern.compile("(.*)(upstream)(.*)");
                Matcher m = p.matcher(tempString);
                if (m.matches()){
                    t1=true;
                }
                p = Pattern.compile("(.*)(proxy_pass)(.*)(http://localhost)(.*)");
                m = p.matcher(tempString);
                if (m.matches()){
                    t2=true;
                }
                System.out.println("line " + line + ": " + tempString);
                line++;
            }
            if (t1&&t2){
                type=3;
                System.out.println("初始化完成");
            }else if (t1&&!t2){
                type=1;
                System.out.println("是建立了upStream，没有建立proxy_pass");
            }else if (!t1&&t2){
                type=2;
                System.out.println("是建立了proxy_pass，没有建立upStream");
            }else if (!t1&&!t2){
                type=0;
                System.out.println("是建立了upStream，没有建立proxy_pass");
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return type;
    }
//建立代理服务
    @Override
    public void initUptStream(String str) {
        File file = new File(str+"\\conf\\nginx.conf");
        File fileOut = new File(str+"\\conf\\nginx123.conf");
        BufferedReader reader = null;
        BufferedWriter bw = null;
        String tempString = null;
        try {
            if (!fileOut.exists()) {
                fileOut.createNewFile();
            }
            FileWriter fw = new FileWriter(fileOut);
            bw = new BufferedWriter(fw);
            reader = new BufferedReader(new FileReader(file));
            int line = 1;
            while((tempString=reader.readLine()) != null){
                Pattern p = Pattern.compile("(.*)(gzip)(.*)");
                Matcher m = p.matcher(tempString);
                bw.write(tempString + "\n");
                if (m.matches()){
                    bw.write("      upstream localhost{" + "\n");
                    bw.write("     " + "\n");
                    bw.write("     }" + "\n");
                }
                line++;
            }
            reader.close();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        file.delete();
        fileOut.renameTo(file);
    }
//建立负载均衡服务器
    @Override
    public void initProxy(String str) {
        File file = new File(str+"\\conf\\nginx.conf");
        File fileOut = new File(str+"\\conf\\nginx123.conf");
        BufferedReader reader = null;
        BufferedWriter bw = null;
        String tempString = null;
        try {
            if (!fileOut.exists()) {
                fileOut.createNewFile();
            }
            FileWriter fw = new FileWriter(fileOut);
            bw = new BufferedWriter(fw);
            reader = new BufferedReader(new FileReader(file));
            int line = 1;
            while((tempString=reader.readLine()) != null){
                Pattern p = Pattern.compile("(.*)(location /)(.*)");
                Matcher m = p.matcher(tempString);
                bw.write(tempString + "\n");
                if (m.matches()){
                    bw.write("       proxy_pass http://localhost;" + "\n");
                    while((tempString=reader.readLine()) != null){
                        if (tempString.contains("}")){
                            bw.write(tempString + "\n");
                            while((tempString=reader.readLine()) != null){
                                bw.write(tempString + "\n");
                            }
                        }
                    }
                }
                line++;
            }
            reader.close();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
            try {
                if (bw != null) {
                    bw.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        file.delete();
        fileOut.renameTo(file);
    }
}
